<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddDialog">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row class="vcenter" :class="['bdbottom',i1===0?'bdtop':'']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row class="vcenter" v-for="(item2,i2) in item1.children" :key="item2.id" :class="[i2 === 0 ? '':'bdtop']">
                  <!-- 渲染二级权限 -->
                  <el-col :span="9">
                    <el-tag closable type="success" @close="removeRightById(scope.row,item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="10">
                    <el-tag closable type="warning" v-for="(item3) in item2.children" :key="item3.id" @close="removeRightById(scope.row,item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column prop="address" label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRolesById(scope.row.id)">删除</el-button>
            <!-- 分配权限按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-user-solid" size="mini" @click="allotRightsDialog(scope.row)">分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" :close-on-click-modal="false" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form ref="addRolesRef" :rules="addFormRules" :model="addRolesForm" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部主体区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="50%" :close-on-click-modal="false" @close="editDialogClosed">
      <!-- 内容主体区域 -->
      <el-form ref="editRolesRef" :rules="addFormRules" :model="editRolesForm" label-width="80px">
        <el-form-item label="角色名称">
          <el-input :value="editRolesForm.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部主体区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 @close="allotDialogClosed"-->
    <el-dialog title="分配权限" :visible.sync="allotDialogVisible" width="50%" :close-on-click-modal="false" @close="setRightDialogVisible">
      <!-- 内容主体区域 -->
      <el-tree ref="treeRef" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" :data="rightsList" :props="TreeProps">

      </el-tree>
      <!-- 底部主体区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'MyRoles',
  data() {
    return {
      // 所有角色列表区数据
      rolesList: [],
      // 所有权限数据
      rightsList: [],
      // 默认选中的节点 Id 值数组
      defKeys: [],
      // 当前即将分配权限角色id
      roleId: '',
      // 添加角色数据
      addRolesForm: {
        // 角色名称
        roleName: '',
        // 角色描述
        roleDesc: ''
      },
      // 编辑角色数据
      editRolesForm: {},
      // 删除角色的 ID
      deleteRolesId: '',
      // 添加角色对话框的显示与隐藏
      addDialogVisible: false,
      // 编辑角色对话框的显示与隐藏
      editDialogVisible: false,
      // 分配权限对话框的显示与隐藏
      allotDialogVisible: false,
      // 添加角色的验证规则对象
      addFormRules: {
        // 角色名称
        roleName: [
          {
            required: true,
            message: '请输入角色名',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 10,
            message: '角色名的长度在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        // 角色描述
        roleDesc: [
          {
            max: 30,
            message: '角色描述的长度不应大于20个字符',
            trigger: 'blur'
          }
        ]
      },
      // 树形空间的属性绑定对象
      TreeProps: {
        label: 'authName',
        children: 'children'
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色的列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = res.data
    },
    // 添加对话框关闭监听事件
    addDialogClosed() {
      this.$refs.addRolesRef.resetFields()
    },
    // 编辑对话框关闭监听事件
    editDialogClosed() {
      this.$refs.editRolesRef.resetFields()
    },
    // 控制添加角色对话框的显示
    showAddDialog() {
      this.addDialogVisible = true
    },
    // 控制编辑角色对话框的显示
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error('获取角色信息失败！')
      this.editRolesForm = res.data
      console.log(this.editRolesForm)
      this.editDialogVisible = true
    },
    // 分配权限对话框的显示
    async allotRightsDialog(role) {
      this.roleId = role.id
      // 获取所有权限数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限数据失败！')
      // 把获取到的权限数据保存到 data 中
      this.rightsList = res.data
      // 递归获取三级节点的 Id
      this.getLeafKeys(role, this.defKeys)
      this.allotDialogVisible = true
    },
    // 添加角色的点击事件
    async addRoles() {
      // 添加表单预验证
      this.$refs.addRolesRef.validate(async valid => {
        if (!valid) return false
        // 可以发起添加角色的网络请求
        const { data: res } = await this.$http.post('roles', this.addRolesForm)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败！')
        this.$message.success('添加角色成功！')
        this.getRolesList()
        this.addDialogVisible = false
      })
    },
    // 编辑角色的点击事件
    async editRoles() {
      // 添加表单预验证
      this.$refs.editRolesRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.put(`roles/${this.editRolesForm.roleId}`, this.editRolesForm)
        if (res.meta.status !== 200) return this.$message.error('更新角色信息失败！')
        this.$message.success('更新角色信息成功！')
        this.getRolesList()
        this.editDialogVisible = false
      })
    },
    // 分配权限的点击事件
    async allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')

      // 数据请求
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('更新权限失败')
      this.$message.success('更新权限成功！')
      this.getRolesList()
      this.allotDialogVisible = false
    },
    // 控制删除角色弹框的显示
    removeRolesById(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${id}`)
          if (res.meta.status !== 200) return this.$message.error('删除失败！')
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getRolesList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 根据Id删除对应的权限
    async removeRightById(role, id) {
      // 根据弹框提示用户是否要删除
      const confirmResult = await this.$confirm('此操作将永久删除该文件，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除！')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败！')
      role.children = res.data
      this.$message.info('删除成功！')
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
    getLeafKeys(node, arr) {
      // 如果当前 node 节点不包含 children 属性，则是三级节点
      if (!node.children) return arr.push(node.id)

      // 如果当前 node 节点包含 children 属性，则继续循环递归
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogVisible() {
      this.defKeys = []
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
  margin: 0 40px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
